Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: only display panics when in debug mode #648

Merged
merged 1 commit into from
Jan 14, 2025

Conversation

gfyrag
Copy link
Contributor

@gfyrag gfyrag commented Jan 13, 2025

No description provided.

@gfyrag gfyrag requested a review from a team as a code owner January 13, 2025 16:31
Copy link

coderabbitai bot commented Jan 13, 2025

Walkthrough

The pull request introduces modifications to the project's routing and middleware handling across multiple files. In the Justfile, a new alias pc is added for the pre-commit target. The API router files (internal/api/router.go, internal/api/v1/routes.go, and internal/api/v2/routes.go) undergo significant changes, primarily involving the removal of custom middleware functionality and the introduction of a custom recovery middleware with enhanced error logging capabilities.

Changes

File Change Summary
Justfile Added pc target as an alias for pre-commit
internal/api/router.go - Replaced middleware.Recoverer with custom recovery middleware
- Added OpenTelemetry error logging
- Integrated middleware directly into router stack
internal/api/v1/routes.go, internal/api/v2/routes.go - Removed service package import
- Deleted middlewares field from routerOptions
- Removed WithMiddlewares function

Possibly related PRs

  • feat: Remove earthly usage #640: The changes in the Justfile related to the pre-commit target and the removal of the earthly target suggest a connection to the modifications made in the Earthfile, which also involved the removal of pre-commit related commands.

Poem

🐰 A Rabbit's Routing Rhyme 🚦

With pc and middleware so neat,
Our router's dance is now complete.
Custom errors, traced with care,
Simplicity beyond compare.
A hop, a skip, our code takes flight! 🚀

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Jan 13, 2025

Codecov Report

Attention: Patch coverage is 31.25000% with 11 lines in your changes missing coverage. Please review.

Project coverage is 81.55%. Comparing base (06d5ff8) to head (8072096).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
internal/api/router.go 31.25% 10 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #648      +/-   ##
==========================================
- Coverage   81.69%   81.55%   -0.15%     
==========================================
  Files         131      131              
  Lines        7070     7059      -11     
==========================================
- Hits         5776     5757      -19     
- Misses        991      999       +8     
  Partials      303      303              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
internal/api/router.go (1)

49-73: Enhance panic recovery with structured error handling.

While the panic recovery logic correctly implements the PR objective of only showing stack traces in debug mode, consider these improvements:

  1. Add structured error response in JSON format
  2. Add structured logging of panics
  3. Consider different handling for different panic types
  4. Consider security implications of exposing stack traces
 func(next http.Handler) http.Handler {
     fn := func(w http.ResponseWriter, r *http.Request) {
         defer func() {
             if rvr := recover(); rvr != nil {
                 if rvr == http.ErrAbortHandler {
                     panic(rvr)
                 }

+                span := trace.SpanFromContext(r.Context())
+                err := fmt.Errorf("%v", rvr)
+                span.RecordError(err)
+
                 if debug {
                     middleware.PrintPrettyStack(rvr)
                 }

-                trace.SpanFromContext(r.Context()).RecordError(fmt.Errorf("%s", rvr))
-
                 w.WriteHeader(http.StatusInternalServerError)
+                w.Header().Set("Content-Type", "application/json")
+                errorResponse := map[string]interface{}{
+                    "error": "Internal Server Error",
+                    "code":  "INTERNAL_ERROR",
+                }
+                if debug {
+                    errorResponse["debug"] = fmt.Sprintf("%v", rvr)
+                }
+                json.NewEncoder(w).Encode(errorResponse)
             }
         }()

         next.ServeHTTP(w, r)
     }

     return http.HandlerFunc(fn)
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06d5ff8 and c10e8f0.

📒 Files selected for processing (4)
  • Justfile (1 hunks)
  • internal/api/router.go (3 hunks)
  • internal/api/v1/routes.go (1 hunks)
  • internal/api/v2/routes.go (0 hunks)
💤 Files with no reviewable changes (1)
  • internal/api/v2/routes.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Tests
🔇 Additional comments (4)
Justfile (1)

7-7: LGTM! Good addition of a shorter alias.

The addition of the pc alias for the pre-commit target improves developer experience by providing a shorter command.

internal/api/v1/routes.go (1)

81-81: LGTM! Good cleanup of router options.

The simplification of routerOptions to only keep the essential tracer field aligns with the removal of custom middleware handling.

internal/api/router.go (2)

48-48: LGTM! Good addition of OTLP middleware.

The addition of OpenTelemetry middleware enhances observability.


104-105: LGTM! Good field reordering.

The reordering of fields in routerOptions improves readability.

@gfyrag gfyrag enabled auto-merge January 14, 2025 13:17
@gfyrag gfyrag force-pushed the feat/only-display-panics-on-debug branch from c10e8f0 to 8072096 Compare January 14, 2025 13:18
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
internal/api/v1/routes.go (1)

Line range hint 37-41: Remove unnecessary middleware.

This middleware function is a pass-through that adds no functionality. Consider removing it to simplify the middleware chain and improve performance.

-			router.Use(func(handler http.Handler) http.Handler {
-				return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-					handler.ServeHTTP(w, r)
-				})
-			})
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c10e8f0 and 8072096.

📒 Files selected for processing (4)
  • Justfile (1 hunks)
  • internal/api/router.go (3 hunks)
  • internal/api/v1/routes.go (1 hunks)
  • internal/api/v2/routes.go (0 hunks)
💤 Files with no reviewable changes (1)
  • internal/api/v2/routes.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • Justfile
  • internal/api/router.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Tests
🔇 Additional comments (1)
internal/api/v1/routes.go (1)

81-81: Verify panic handling configuration.

With the removal of custom middleware support, ensure that panic handling is properly configured at a higher level (e.g., in the main router or recovery middleware) to control panic displays based on the debug mode.

Let's verify the panic handling configuration:

✅ Verification successful

Panic handling is properly configured

The panic handling is correctly implemented at the router level with debug mode awareness through middleware.PrintPrettyStack. The removal of custom middleware support from routerOptions doesn't impact this functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for panic handling configuration in the main router or recovery middleware.

# Look for panic handling or recovery middleware
rg -A 5 'recovery|panic|debug.*mode' internal/api/

# Look for debug mode configuration
rg -A 5 'debug.*=|debug.*bool' internal/api/

Length of output: 2266

@gfyrag gfyrag added this pull request to the merge queue Jan 14, 2025
Merged via the queue into main with commit 67e169d Jan 14, 2025
8 of 10 checks passed
@gfyrag gfyrag deleted the feat/only-display-panics-on-debug branch January 14, 2025 15:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants